import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import {
  Modal,
  Button,
  Form,
  Row,
  Col,
  Input,
  DatePicker,
  Divider,
  Card,
  Select,
  Progress,
  Spin,
  Tag,
} from 'antd';
import { connect } from 'dva';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import pageListHelp from '@/utils/pageListHelp';
import styles from '../search.less';
import { encode } from '@/utils/AesUtil';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
@connect(
  state => ({
    taskHistory: state.taskHistory,
    dataqueryPageList: state.taskHistory.dataqueryPageList,
    loadingqueryPageList: state.loading.effects['taskHistory/queryPageList'],
  }),
  dispatch => ({
    queryPageList: e => dispatch({ type: 'taskHistory/queryPageList', payload: e }),
    deleteByIds: e => dispatch({ type: 'taskHistory/deleteByIds', payload: e }),
    queryListById: e => dispatch({ type: 'taskHistory/queryListById', payload: e }),
    stopTask: e => dispatch({ type: 'taskHistory/stopTask', payload: e }),
    dispatch,
  })
)
@Form.create()
class AuditTaskHistory extends PureComponent {
  state = { selectedRows: [], formValues: {}, executionPolicyId: null };
  componentDidMount() {
    const {
      location: {
        query: { executionPolicyId },
      },
    } = this.props;
    if (executionPolicyId) {
      this.setState({ executionPolicyId }, () => this.pageList());
    } else {
      this.pageList();
    }
  }
  // componentDidUpdate(prevProps) {
  //   pageListHelp('dataqueryPageList', prevProps, this);
  // }
  componentWillUnmount() {
    window.clearTimeout(window.setTimeoutHistory);
  }
  // 判断进度条是正数
  isIntNum = val => {
    var reg = /^\d+(?=\.{0,1}\d+$|$)/;
    if (reg.test(val)) {
      return true;
    } else {
      return false;
    }
  };

  columns = [
    { title: '执行序号', dataIndex: 'historyId', ellipsis: true, width: 80 },
    // {
    //   title: '任务类型',
    //   dataIndex: 'executionPolicyType',
    //   ellipsis: true,
    //   render: executionPolicyType =>
    //     (
    //       [
    //         { executionPolicyType: 1, auditTaskTypeName: '全量/增量' },
    //         { executionPolicyType: 2, auditTaskTypeName: '抽样' },
    //       ].find(item => item.executionPolicyType == executionPolicyType) || {}
    //     ).auditTaskTypeName,
    // },
    { title: '任务名称', dataIndex: 'executionPolicyName', ellipsis: true },
    {
      title: '执行开始时间',
      dataIndex: 'beginTime',
      render: text => text && moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '执行结束时间',
      render: text =>
        text.executionStatus == 1
          ? '正在执行中'
          : text.endTime && moment(text.endTime).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '执行状态',
      dataIndex: 'executionStatus',
      render: text => (
        <Tag color={{ 1: 'blue', 2: 'green', 3: 'red' }[text]}>
          {{ 1: '执行中', 2: '已完成', 3: '已终止' }[text]}
        </Tag>
      ),
    },
    {
      title: '执行进度',
      ellipsis: true,
      align: 'cenrer',
      render: text =>
        this.isIntNum(text.speedProgress) && (
          <Progress
            percent={text.speedProgress}
            size="small"
            status={{ 1: 'active', 2: null, 3: 'exception' }[text.executionStatus]}
            title={text.executionStatus == 3 ? `${text.speedProgress}%` : null}
          />
        ),
    },
    {
      title: '执行时长',
      dataIndex: 'exeDuration',
      ellipsis: true,
      render: text => {
        let hours = parseInt(text / (1000 * 60 * 60));
        let minutes = parseInt((text % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = Math.round((text % (1000 * 60)) / 1000);
        if (text) {
          if (text < 1000) {
            return `${text}毫秒`;
          } else if (text < 60000) {
            return `${seconds}秒`;
          } else if (text < 3600000) {
            return `${minutes}分${seconds}秒`;
          } else if (text > 3600000) {
            return `${hours}小时${minutes}分${seconds}秒`;
          }
        } else {
          return '--';
        }
      },
    },
    {
      title: '操作',
      width: 150,
      render: text => (
        <Fragment>
          {/* {text.executionStatus == 1 ? (
            <a onClick={() => this.stopTask(text.historyId)}>停止任务</a>
          ) : (
            <> */}
          <a onClick={() => this.deleteData(text.historyId)}>删除</a>
          <Divider type="vertical" />
          <a
            onClick={() =>
              this.props.history.push({
                pathname: '/taskInfo/taskHistory/report',
                query: {
                  taskId: text.taskId,
                  historyId: text.historyId,
                },
              })
            }
          >
            查看报告
          </a>
          {/* </>
          )} */}
        </Fragment>
      ),
    },
  ];
  stopTask = id => {
    Modal.confirm({
      title: '停止任务',
      content: '您确认要停止任务吗（任务停止后无法恢复进度）？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleStopTask(id),
    });
  };
  handleStopTask = historyId => {
    return this.props.stopTask({ historyId }).then(res => {
      if (res.result == 'ok') {
        Modal.success({ title: res.msg });
        this.pageList();
      } else {
        Modal.error({ title: '操作失败', content: res.msg });
      }
    });
  };

  //删除
  deleteData = id => {
    Modal.confirm({
      title: '删除',
      content: '您确认要删除选择的数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };
  //批量删除
  batchDelete = (rows = []) => {
    this.deleteData(rows);
  };
  handleThisRowDelete = historyIds => {
    return this.props.deleteByIds({ historyIds }).then(res => {
      if (res.result == 'ok') {
        Modal.success({ title: res.msg });
        this.pageList();
        this.setState({ selectedRows: [] });
      } else {
        Modal.error({ title: '操作失败', content: res.msg });
      }
    });
  };

  // 分页查询列表
  pageList(pageSize = 10, pageNum = 0) {
    // 清除之前旧的定时任务
    window.clearTimeout(window.setTimeoutHistory);
    const { queryPageList } = this.props;
    const { formValues, executionPolicyId } = this.state;
    const values = {
      pageSize: this.state.pagination ? this.state.pagination.pageSize : pageSize,
      pageNum: this.state.pagination ? this.state.pagination.current - 1 : pageNum,
      executionPolicyType: formValues.executionPolicyType,
      executionPolicyName: formValues.executionPolicyName,
      executionPolicyId,
      beginTime:
        formValues.rangeTime && formValues.rangeTime.length
          ? formValues.rangeTime[0].format('YYYY-MM-DD HH:mm:ss')
          : '',
      endTime:
        formValues.rangeTime && formValues.rangeTime.length
          ? formValues.rangeTime[1].format('YYYY-MM-DD HH:mm:ss')
          : '',
    };
    queryPageList(values).then(() => {
      // 校验是否有未完成的任务，如果有开始调用定时任务
      if (this.checkProgress()) {
        this.startTimer();
      }
    });
  }
  // 校验当前页是否有未完成的任务，并返回未完成任务的Id集合
  checkProgress = () => {
    const { dataqueryPageList } = this.props;
    const executingArr = dataqueryPageList.dataList.filter(item => item.executionStatus === 1);
    if (executingArr.length) {
      const idArr = executingArr.map(item => item.historyId);
      return idArr;
    } else {
      return false;
    }
  };
  // 定时调用未完成的任务历史
  startTimer = () => {
    const { queryListById } = this.props;
    // 清除之前旧的定时任务
    window.clearTimeout(window.setTimeoutHistory);
    if (this.checkProgress()) {
      queryListById({ historyIds: this.checkProgress() }).then(() => {
        if (this.checkProgress()) {
          window.setTimeoutHistory = setTimeout(() => {
            this.startTimer();
          }, 3000);
        }
      });
    }    
  };

  // 分页请求
  handleStandardTableChange(pagination) {
    this.setState({ pagination }, () => this.pageList());
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState(
        {
          formValues: values,
          pagination: '',
        },
        () => this.pageList()
      );
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          {/* <Col md={6} sm={24}>
            <FormItem label="任务类型">
              {getFieldDecorator('executionPolicyType')(
                <Select placeholder="请选择">
                  <Select.Option value="">全部</Select.Option>
                  {[
                    { executionPolicyType: 1, auditTaskTypeName: '全量/增量' },
                    { executionPolicyType: 2, auditTaskTypeName: '抽样' },
                  ].map(item => (
                    <Select.Option key={item.executionPolicyType} value={item.executionPolicyType}>
                      {item.auditTaskTypeName}
                    </Select.Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col> */}

          <Col md={8} sm={24}>
            <FormItem label="任务名称">
              {getFieldDecorator('executionPolicyName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem {...formLayout} label="执行时间">
              {getFieldDecorator('rangeTime')(
                <RangePicker
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['开始', '结束']}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  render() {
    const { loadingqueryPageList, dataqueryPageList } = this.props;
    const { selectedRows } = this.state;
    return (
      <PageHeaderWrapper title="任务历史">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
            {selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
              )}             
            </div>
            <TableList
              size="middle"
              selectedRows={selectedRows}
              loading={loadingqueryPageList}
              rowSelection={{
                selectedRowKeys: this.state.selectedRows,
                onChange: e => this.setState({ selectedRows: e }),
              }}
              data={dataqueryPageList}
              rowKey="historyId"
              columns={this.columns}
              hideRowSelection
              onChange={this.handleStandardTableChange.bind(this)}
            />
          </div>
          {this.props.location.query.executionPolicyId && (
            <div style={{ textAlign: 'center' }}>
              <br />
              <Button type="primary" onClick={() => this.props.history.goBack()}>
                返回
              </Button>
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default AuditTaskHistory;
